<!-- 场景编辑/详情 -->
<!-- powerType 为1是只读,为2是可编辑 -->
<template>
  <div class="app-container">
    <Edialog
      :outershow="outershow"
      :title="title"
      @saveFn="saveFn"
      @close="closeFn"
      :saveClick="type == 'editConfig' ? true : false"
      width="70%"
    >
      <el-row :gutter="20" v-loading="loading">
        <el-row :gutter="20">
          <el-form
            :rules="rules"
            :model="setOf"
            ref="setOf"
            label-width="100px"
          >
            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="场景编码" prop="sceneCode">
                  <span>{{ setOf.sceneCode }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <div style="font-size: 14px">
                  <el-form-item label="场景名称" prop="sceneName">
                    <span>{{ setOf.sceneName }}</span>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </el-row>
        <el-col :span="24">
          <SpreadSheet
            v-loading="sheetLoading"
            v-if="outershow"
            style="height: 55vh; width: 100%"
            ref="Sheet"
            SheetName="Sheet1"
            :File="file"
            :ColumnWidth="200"
            @loaded="loaded"
            @cell-selected="cellSelected"
            @change="sheetChange"
            @cell-edited="cellEdited"
            :onlyRead="type == 'editConfig' ? false : true"
          ></SpreadSheet>
          <el-radio-group
            v-model="tabPosition"
            style="margin-top: 20px"
            size="small"
          >
            <el-radio-button
              :label="item.templateName"
              v-for="item in sceneTemplateList"
              :key="item.id"
              @click.native="changeSceneTemplate(item)"
              >{{
                item.templateCode + "-" + item.templateName || "模板名称"
              }}</el-radio-button
            >
          </el-radio-group>
        </el-col>
      </el-row>
    </Edialog>
    <subject_choose
      v-if="isShowDialog"
      @close="closeDialog"
      @successFn="successFn"
      ref="subject_choose"
    ></subject_choose>
  </div>
</template>

<script>
import {
  indexToCoord,
  getNonEmptyMergedCells,
  updateCellAttributesByCondition,
  findChangedCells,
  updateCellAttributes,
  coordToIndex,
  findCellsByPowerType,
} from "@/utils/spreadsheet.js";
import SpreadSheet from "@/components/Xspreadsheet/SpreadSheet.vue";
import Edialog from "@/components/Edialog";
import subject_choose from "@/components/Xspreadsheet/subject_choose.vue";
import {
  putSceneInfoApi,
  postSceneInfoApi,
  deleteSceneInfoByIds,
  SceneInfoApi,
  SceneInfoByIdApi,
  SceneInfoCopyByIdApi,
  putSceneTemplateApi,
  postSceneTemplateApi,
  SceneTemplateCopyByIdApi,
  deleteSceneTemplateByIds,
  SceneTemplateApi,
  SceneTemplateByIdApi,
  putSceneTemplateEditorTemplateApi,
} from "@/api/sceneManage";
import { result } from "lodash";
export default {
  data() {
    return {
      tabPosition: "",
      setOf: {
        sceneCode: "",
        sceneName: "",
      },
      rules: {
        sceneName: [
          { required: true, message: "场景编码不能为空", trigger: "blur" },
        ],
        sceneCode: [
          { required: true, message: "场景编码不能为空", trigger: "blur" },
        ],
      },
      isShowDialog: false,
      tableData: [],
      loading: false,
      tableHeight: "calc(60vh - 186px)",
      //表格字段
      tableColumns: [
        {
          prop: "templateCode",
          label: "模板编码",
        },
        {
          prop: "templateName",
          label: "模板名称",
        },
        { prop: "subjectNum", label: "科目数量" },
        { prop: "editorSubjectNum", label: "编辑数量" },
      ],
      file: null,
      ColumnCount: 30,
      RowCount: 100,
      headers: [],
      records: [],

      outershow: false,
      title: "场景编辑",

      sceneTemplateList: [],
      type: "",
      sheetLoading: false,
    };
  },
  components: {
    Edialog,
    SpreadSheet,
    subject_choose,
  },
  methods: {
    changeSceneTemplate(item) {
      // console.log("回显", item);
      this.sheetLoading = true;
      if (item.updatedExcelJson) {
        this.$nextTick(() => {
          this.$refs.Sheet.loadData(JSON.parse(item.updatedExcelJson) || []);
        });
      } else {
        let updatedExcelJson = JSON.parse(this.$cloneDeep(item.excelJson));
        //updatedExcelJson:根据powerType == 1加上editable属性的json 用于在场景编辑时预览
        this.$set(
          item,
          "updatedExcelJson",
          JSON.stringify(
            updateCellAttributesByCondition(
              updatedExcelJson,
              "editable",
              false,
              (cell) => cell.powerType == "1"
            )
          )
        );

        //用于后面比对发生变化的源数组
        // this.$set(
        //   item,
        //   "updatedExcelJsonSource",
        //   JSON.stringify(
        //     updateCellAttributesByCondition(
        //       updatedExcelJson,
        //       "editable",
        //       false,
        //       (cell) => cell.powerType == "1"
        //     )
        //   )
        // );
        //为后续有修改的单元格添加值
        if (item.values && item.values.length > 0) {
          item.values.forEach((x) => {
            console.log("x", x);
            let { rowIndex, colIndex } = coordToIndex(x.subjectCode);
            let excelJson = this.$cloneDeep(item.updatedExcelJson);
            item.updatedExcelJson = JSON.stringify(
              updateCellAttributes(
                rowIndex,
                colIndex,
                {
                  text: x.subjectValue,
                  result: x.subjectValue,
                  formula: "",
                  subjectSign: x.subjectSign,
                },
                JSON.parse(excelJson)
              )
            );
          });
        }
        this.$nextTick(() => {
          let itemUpdatedExcelJson = this.$cloneDeep(item.updatedExcelJson);
          //用于后面比对发生变化的源数组（拼接好数据的json在场景管理里面才是当前的原数组，项目管理同理）
          this.$set(item, "updatedExcelJsonSource", itemUpdatedExcelJson);
          this.$refs.Sheet.loadData(JSON.parse(item.updatedExcelJson) || []);
        });
      }

      setTimeout(() => {
        console.log("xs.datas", xs.datas);
        //可编辑单元格加入黄色背景
        let editableCell = findCellsByPowerType(
          JSON.parse(item.updatedExcelJson),
          2
        );
        console.log(
          "JSON.parse(item.updatedExcelJson)change",
          JSON.parse(item.updatedExcelJson),
          editableCell
        );
        if (editableCell.length > 0) {
          editableCell.forEach((e) => {
            let { rowIndex, colIndex } = coordToIndex(e.address);
            let cell = xs.sheet.data.getCell(rowIndex, colIndex);
            xs.datas.forEach((row) => {
              // console.log("row", row.styles[cell.style]);
              this.$set(row.styles, cell.style, {
                border: {
                  top: ["thin", "#000000"],
                  bottom: ["thin", "#000000"],
                  left: ["thin", "#000000"],
                  right: ["thin", "#000000"],
                },
                //黄色
                bgcolor: "#ffff00",
                textwrap: true,
                // color: "#900b09",
                align: "center",
                valign: "middle",
                border: {
                  top: ["thin", "#1E1E1E"],
                  bottom: ["thin", "#1E1E1E"],
                  right: ["thin", "#1E1E1E"],
                  left: ["thin", "#1E1E1E"],
                },
                font: {
                  bold: false,
                },
              });
              xs.reRender();
            });
          });
        }
        this.sheetLoading = false;
      }, 500);
    },
    successFn(e) {
      console.log("选择成功", e);
    },
    closeDialog() {
      this.isShowDialog = false;
    },
    templatechooseFn() {
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.$refs.subject_choose.manufacturerOpen();
      });
    },

    cellSelected(cell, ri, ci) {
      console.log("cellSelected", cell, ri, ci);
    },
    sheetChange(data) {
      this.sceneTemplateList.forEach((item) => {
        if (item.templateName == this.tabPosition) {
          let ChangedCells =
            findChangedCells(JSON.parse(item.updatedExcelJsonSource), data) ||
            [];
          console.log("修改的单元格", ChangedCells);

          if (ChangedCells.length > 0) {
            ChangedCells.forEach((cell) => {
              //因为如果复制会导致单元格里面的所有属性都被复制，所以这里只修改text属性
              let { rowIndex, colIndex } = coordToIndex(
                cell.originalCell.address
              );
              let excelJson = this.$cloneDeep(item.updatedExcelJson);
              item.updatedExcelJson = JSON.stringify(
                updateCellAttributes(
                  rowIndex,
                  colIndex,
                  {
                    text: cell.updatedCell.text || "",
                    address: cell.originalCell.address,
                    //编辑类型：0：删除；1新增或者修改
                    operType: cell.updatedCell.text ? 1 : 0,
                  },
                  JSON.parse(excelJson)
                )
              );
            });
          }
        }
      });
    },
    //监听不到直接删除或者复制粘贴到单元格的数据变更
    cellEdited(cell, ri, ci) {
      //让修改同步到要提交的excelJson中,要提交的excelJson是没有根据powerType == 1加上editable属性的json
      // this.sceneTemplateList.forEach((item) => {
      //   if (item.templateName == this.tabPosition) {
      //     let excelJson = this.$cloneDeep(item.updatedExcelJson);
      //     item.updatedExcelJson = JSON.stringify(
      //       updateCellAttributes(
      //         ri,
      //         ci,
      //         {
      //           text: cell.text || "",
      //           address: indexToCoord(ri, ci),
      //           //编辑类型：0：删除；1新增或者修改
      //           operType: cell.text ? 1 : 0,
      //         },
      //         JSON.parse(excelJson)
      //       )
      //     );
      //   }
      // });
      // console.log("cellEdited", cell, ri, ci);
    },
    //表格数据加载事件
    loaded(spreadsheet) {
      // console.log("loaded", JSON.stringify(spreadsheet));
    },
    //外部打开弹窗
    async openFn(type, data) {
      this.loading = true;
      this.outershow = true;
      this.type = type;
      this.title = type === "editConfig" ? "场景编辑" : "详情";

      if (data && data.id) {
        this.sceneId = data.id;
        let res = await SceneInfoByIdApi(data.id);
        if (res.data && res.data.bcode == 0) {
          let x = res.data.bdata;
          this.setOf.sceneCode = x.sceneCode;
          this.setOf.sceneName = x.sceneName;
          this.sceneTemplateList = x.sceneTemplateList;
          console.log("data", JSON.parse(x.sceneTemplateList[0].excelJson));
          if (this.sceneTemplateList.length > 0) {
            this.tabPosition = this.sceneTemplateList[0].templateName;
            // this.sceneTemplateList.forEach((item) => {
            // let updatedExcelJson = JSON.parse(
            //   this.$cloneDeep(this.sceneTemplateList[0].excelJson)
            // );
            //updatedExcelJson:根据powerType == 1加上editable属性的json 用于在场景编辑时预览
            // this.$set(
            //   this.sceneTemplateList[0],
            //   "updatedExcelJson",
            //   JSON.stringify(
            //     updateCellAttributesByCondition(
            //       updatedExcelJson,
            //       "editable",
            //       false,
            //       (cell) => cell.powerType == "1"
            //     )
            //   )
            // );
            //用于后面比对发生变化的源数组
            // this.$set(
            //   this.sceneTemplateList[0],
            //   "updatedExcelJsonSource",
            //   JSON.stringify(
            //     updateCellAttributesByCondition(
            //       updatedExcelJson,
            //       "editable",
            //       false,
            //       (cell) => cell.powerType == "1"
            //     )
            //   )
            // );
            // });
            // if (
            //   this.sceneTemplateList[0].values &&
            //   this.sceneTemplateList[0].values.length > 0
            // ) {
            //   this.sceneTemplateList[0].values.forEach((item) => {
            //     let { rowIndex, colIndex } = coordToIndex(item.subjectCode);
            //     let excelJson = this.$cloneDeep(
            //       this.sceneTemplateList[0].updatedExcelJson
            //     );
            //     this.sceneTemplateList[0].updatedExcelJson = JSON.stringify(
            //       updateCellAttributes(
            //         rowIndex,
            //         colIndex,
            //         {
            //           text: item.subjectValue,
            //           result: item.subjectValue,
            //           formula: "",
            //         },
            //         JSON.parse(excelJson)
            //       )
            //     );
            //   });
            //   console.log(
            //     "单元格数据赋值1",
            //     JSON.parse(this.sceneTemplateList[0].updatedExcelJson)
            //   );
            // }
            this.$nextTick(() => {
              this.changeSceneTemplate(this.sceneTemplateList[0]);
            });
          }
        } else {
          this.sceneId = "";
          this.setOf.sceneCode = "";
          this.setOf.sceneName = "";
          this.sceneTemplateList = [];
        }
      }
      this.loading = false;
    },
    saveFn() {
      let templates = [];
      this.sceneTemplateList.forEach((item) => {
        if (item && item.updatedExcelJson) {
          console.log(
            "????????????",
            JSON.parse(item.updatedExcelJsonSource),
            JSON.parse(item.updatedExcelJson)
          );

          const changedCells = findChangedCells(
            JSON.parse(item.updatedExcelJsonSource),
            JSON.parse(item.updatedExcelJson)
          );
          console.log("changedCells", changedCells);
          let valuesList = [];
          changedCells.forEach((cell) => {
            valuesList.push({
              // subjectCode: cell.updatedCell.address,
              subjectSign: cell.updatedCell.subjectSign,
              subjectValue: cell.updatedCell.text || "",
              operType: cell.updatedCell.operType || 0, //编辑类型：0：删除；1新增或者修改
            });
          });
          templates.push({
            templateId: item.templateId,
            valuesList: valuesList,
          });
        }
      });
      let params = {
        sceneId: this.sceneId,
        templates: templates,
      };
      console.log("templates", templates);

      putSceneTemplateEditorTemplateApi(params).then((res) => {
        if (res.data && res.data.bcode == 0) {
          this.$message.success("保存成功");
          this.closeFn();
          this.$emit("refreshFn");
        }
      });
    },
    closeFn() {
      this.outershow = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.el-form-item {
  width: 45%;
  // display: flex;
}
::v-deep .el-form-item__content {
  width: 60% !important;
}
.ellipsis_text {
  width: 200px; /* 或者你希望的固定宽度 */
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出容器的文本 */
  text-overflow: ellipsis; /* 使用省略号表示超出容器的文本 */
}
</style>
